package io.github.eric.urpc.example.example;

import io.github.eric.urpc.client.Client;
import io.github.eric.urpc.client.ClientConfig;
import io.github.eric.urpc.core.rpc.RpcContext;
import io.github.eric.urpc.core.rpc.RpcController;
import io.github.eric.urpc.core.rpc.RpcMethod;
import io.github.eric.urpc.example.SimpleServer;
import io.github.eric.urpc.example.msg.EchoMsg;
import io.netty.handler.logging.LogLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Random;


public class EchoServerExample {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServerExample.class);

    public static void main(String[] args) throws Exception {

        SimpleServer simpleServer = new SimpleServer();
        simpleServer.start();

        // init config
        ClientConfig clientConfig = new ClientConfig.Builder()
                .applicationName("simpleClient")
                .nettyLoggingLevel(LogLevel.DEBUG)
                .serverHost("127.0.0.1")
                .serverPort(52379)
                // set controllers
                .rpcControllers(Collections.singletonList(new RpcController() {
                    @RpcMethod
                    public void onEchoMessage(RpcContext rpcContext, EchoMsg msg) {
                        LOGGER.info("Client receive a TestMessage, msg: {}, sendAt: {} from {}", msg.getMsg(), msg.getSendAt(), rpcContext.getRemoteAddress());
                    }
                }))
                .build();

        // init client and connect to server
        Client client = new Client(clientConfig);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(3000L);

                        LOGGER.info("urpc client send msg to urpc server");
                        EchoMsg echoMsg = new EchoMsg();
                        Random r = new Random();
                        echoMsg.setOrderedThreadKey(r.nextInt(10)+"");
                        client.sendAsync(echoMsg);
                    } catch (Exception ignore) {
                        LOGGER.error("error", ignore);
                    }
                }
            }
        }).start();
    }
}
